/*
* 使用模板测试
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "../common/LoadShaders.h"
#include "../include/vmath.h"

#define BUFFER_OFFSET(offset) ((void*) (offset))

const unsigned int SCR_WIDTH = 512;
const unsigned int SCR_HEIGHT = 512;

void processInput(GLFWwindow *window)
{
    if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
    {
        //将窗口设置为关闭，跳出循环
        glfwSetWindowShouldClose(window, 1);
    }
}

void framebuffer_size_callback(GLFWwindow* window, int width, int height);

enum VAO_IDs { Triangles, NumVAOs };
enum Buffer_IDs { ArrayBuffer, NumBuffers };
enum Attrib_IDs { vPosition = 0, vColor=1 };

//GLuint VAOs[NumVAOs];
//GLuint Buffers[NumBuffers];

GLuint ebo[1];
GLuint vao[1];
GLuint vbo[1];

GLuint position_buffer;
GLuint color_buffer;
GLuint model_matrix_buffer;
GLuint color_tbo;
GLuint model_matrix_tbo;

const GLuint NumVertices = 9;
GLint render_view_matrix_loc;
GLint render_projection_matrix_loc;
float aspect = 1.0;

int position_loc;
int color_loc;

struct VectexData {
    unsigned char color[4];
    float position[4];
};

const VectexData vertices[NumVertices] = {
    {{255,   0,   0, 255}, {-0.90, -0.90,  1.0 }}, //triangle 1
    {{  0, 255,   0, 255}, {  0.5, -0.45, -1.0 }},
    {{  0,   0, 255, 255}, {-0.90,  0.85,  1.0 }},

    {{ 10,  10,  10, 255}, {   0,  -0.25, -1.0 }}, //triangle 2
    {{100, 100, 100, 255}, { 0.90, -0.90,  1.0 }},
    {{255, 255, 255, 255}, { 0.85,  0.90,  1.0 }},

    {{255, 255, 255, 255}, {-0.50, -0.50,  1.0 }}, // mask triangle 1
    {{255, 255, 255, 255}, {  0.5, -0.50,  1.0 }},
    {{255, 255, 255, 255}, {-0.50,  0.50,  1.0 }},

};

void init(void)
{
    glClearColor(0, 0, 0, 1);

    ShaderInfo shaders[] = {
        { GL_VERTEX_SHADER, "triangles.vert" },
        { GL_FRAGMENT_SHADER, "triangles.frag" },
        { GL_NONE, NULL }
    };

    GLuint program = LoadShaders(shaders);
    glUseProgram(program);

    render_view_matrix_loc = glGetUniformLocation(program, "view_matrix");
    render_projection_matrix_loc = glGetUniformLocation(program, "projection_matrix");

    position_loc = glGetAttribLocation(program, "vPos");
    color_loc = glGetAttribLocation(program, "vColor");


    // set vertex property
    glGenVertexArrays(1, vao);
    glBindVertexArray(vao[0]);


    glGenBuffers(1, vbo);
    glBindBuffer(GL_ARRAY_BUFFER, vbo[0]);
    glBufferData(GL_ARRAY_BUFFER,
                 sizeof(vertices),
                 vertices,
                 GL_STATIC_DRAW);   

    glVertexAttribPointer(color_loc, 4, GL_UNSIGNED_BYTE,
                          GL_TRUE,
                          sizeof(VectexData),
                          BUFFER_OFFSET(0));

    glVertexAttribPointer(position_loc, 2, GL_FLOAT,
                          GL_FALSE,
                          sizeof(VectexData),
                          BUFFER_OFFSET(sizeof(vertices[0].color)));



    glEnableVertexAttribArray(position_loc);
    glEnableVertexAttribArray(color_loc);

    glClearStencil(0x0);

    glEnable(GL_DEPTH_TEST);
    glEnable(GL_STENCIL_TEST);

}

void display(void)
{
    vmath::mat4 view_matrix;

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glBindVertexArray(vao[0]);

    static int time = 0;
    time += 1;
    static bool flag = true;

    if(time > 500)
    {
        time = 0;
        flag = !flag;
    }

    glStencilFunc(flag ? GL_EQUAL : GL_NOTEQUAL, 0x1, 0x1); // 模板比较函数
    glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
    glDrawArrays(GL_TRIANGLES, 0, 3);

    glStencilFunc(flag ? GL_NOTEQUAL : GL_EQUAL, 0x1, 0x1);
    glDrawArrays(GL_TRIANGLES, 3, 3);

    // draw mask
    glBindVertexArray(vao[0]);
    glDrawArrays(GL_TRIANGLES, 6,  3);

    glFlush();
}


int main()
{
    //glfw初始化
    glfwInit();
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

    //glfw创建窗口
    GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "OpenGL编程指南", NULL, NULL);

    if (window == NULL)
    {
        printf("创建窗口失败");
        //终止
        glfwTerminate();
        return -1;
    }

    //显示窗口
    glfwMakeContextCurrent(window);

    //设置回调，当窗口大小调整后将调用该回调函数
    glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);

    // glad初始化
    if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
    {
        printf("加载失败");
        return -1;
    }

    init();

    // 使用循环达到循环渲染效果
    while (!glfwWindowShouldClose(window))
    {
        display();
        //自定义输入事件
        processInput(window);
        //交互缓冲区，否则显示空白
        glfwSwapBuffers(window);
        //输入输出事件,否则无法对窗口进行交互
        glfwPollEvents();
    }

    //终止渲染 关闭并清理glfw本地资源
    glfwTerminate();
    return 0;
}


void framebuffer_size_callback(GLFWwindow* window, int width, int height)
{
    glViewport(0, 0, width, height);

    glClear(GL_STENCIL_BUFFER_BIT);
    glStencilFunc(GL_ALWAYS, 0x1, 0x1);
    glStencilOp(GL_REPLACE, GL_REPLACE, GL_REPLACE);

    // draw mask
    glBindVertexArray(vao[0]);
    glDrawArrays(GL_TRIANGLES, 6,  3);

}
